package com.alibaba.nacos.core.auth;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 资源方法请求
 *
 * @author luojing
 * @date 2020/09/15
 */
public class RequestResFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ResProperties properties;

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String requestUri = request.getRequestURI();
        String method = request.getMethod();
        Optional<Boolean> any = properties.getSubfixs()
            .stream()
            .parallel()
            .map(subfix -> StringUtils.endsWith(requestUri, subfix))
            .filter(b -> b)
            .findAny();
        if (any.isPresent() && (!StringUtils.equals("GET", method) && !StringUtils.equals("OPTIONS", method))) {
            wrapDisAllowed(resp);
        } else {
            filterChain.doFilter(req, resp);
        }
    }

    private void wrapDisAllowed(ServletResponse servletResponse) {
        try {
            writeTextToResponse((HttpServletResponse) servletResponse, 500, "UTF-8", "text/plain", "请求静态资源请使用GET方法。");
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    void writeTextToResponse(HttpServletResponse response, int status, String encoding, String contentType, String content) throws IOException {
        response.setStatus(status);
        response.setCharacterEncoding(encoding);
        response.setContentType(contentType);
        response.getWriter().print(content);
        // response.getWriter().flush();
    }

}
